import _ from 'lodash';
import urllib from 'url';
import request from 'request';
import logger from '../common/logger';

const ALLOW_HOSTNAME = [
  'avatars.githubusercontent.com', 'www.gravatar.com',
  'gravatar.com', 'www.google-analytics.com',
];

export default function (req, res, next) {
  const url = decodeURIComponent(req.query.url);
  const hostname = urllib.parse(url).hostname;

  if (ALLOW_HOSTNAME.indexOf(hostname) === -1) {
    return res.send(`${hostname} is not allowed`);
  }

  request.get({
    url,
    headers: _.omit(req.headers, ['cookie', 'refer']),
  })
    .on('response', (response) => {
      res.set(response.headers);
    })
    .on('error', (err) => {
      logger.error(err);
    })
    .pipe(res);
}
